// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RemotableEventHandler.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework
{
    #region Usings

    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Org.OpenTrader.Framework.Events;

    #endregion

    /// <summary>
    /// The ot event handler.
    /// </summary>
    /// <typeparam name="T">
    /// The event args
    /// </typeparam>
    public class RemotableEventHandler<T> : RemotingStub
        where T : AbstractEventArgs
    {
        #region Constants and Fields

        /// <summary>
        /// The chaining.
        /// </summary>
        private readonly IDictionary<RemotableEventHandler<T>, EventHandler<T>> chaining =
            new Dictionary<RemotableEventHandler<T>, EventHandler<T>>();

        /// <summary>
        /// The chainingReverse.
        /// </summary>
        private readonly IDictionary<EventHandler<T>, RemotableEventHandler<T>> chainingReverse =
            new Dictionary<EventHandler<T>, RemotableEventHandler<T>>();

        /// <summary>
        /// The lock.
        /// </summary>
        // private readonly ILocker locker = new Locker();
        /// <summary>
        /// The subscribers.
        /// </summary>
        private readonly IList<EventHandler<T>> subscribers = new List<EventHandler<T>>();

        /// <summary>
        /// The debug.
        /// </summary>
        private static bool debug = false;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RemotableEventHandler{T}"/> class.
        /// </summary>
        /// <param name="name">
        /// The name of this RemotableEventHandler
        /// </param>
        public RemotableEventHandler(string name)
        {
            this.Name = name;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets SubscribersCount.
        /// </summary>
        public int SubscribersCount
        {
            get
            {
                {
                    // lock (this.locker)
                    return this.subscribers.Count;
                }
            }
        }

        /// <summary>
        /// Gets or sets Name.
        /// </summary>
        protected string Name { get; set; }

        #endregion

        #region Operators

        /// <summary>
        /// To be able to +=
        /// </summary>
        /// <param name="handler">
        /// The handler.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>this RemotableEventHandler</returns>
        public static RemotableEventHandler<T> operator +(RemotableEventHandler<T> handler, EventHandler<T> callback)
        {
            handler.Subscribe(callback);
            return handler;
        }

        /// <summary>
        /// To be able to -=
        /// </summary>
        /// <param name="handler">
        /// The handler.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>this RemotableEventHandler</returns>
        public static RemotableEventHandler<T> operator -(RemotableEventHandler<T> handler, EventHandler<T> callback)
        {
            handler.Unsubscribe(callback);
            return handler;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The chain.
        /// </summary>
        /// <param name="handlerDestination">
        /// The handlerDestination.
        /// </param>
        public void Chain(RemotableEventHandler<T> handlerDestination)
        {
            // handlerSource += handlerDestination.GetChainingHandler(handlerSource);
            this.Subscribe(handlerDestination.GetChainingHandler(this));
        }

        /// <summary>
        /// Raise the event on this RemotableEventHandler
        /// </summary>
        /// <param name="sender">
        /// The senderof the event.
        /// </param>
        /// <param name="args">
        /// The event arguments.
        /// </param>
        public virtual void RaiseEvent(object sender, T args)
        {
            var space = string.Empty;
            {
                // lock (this.locker)
                if (this.subscribers.Count > 0)
                {
                    args.Hops++;

                    if (debug)
                    {
                        space = PrettyPrinter.Timings.Format(Timings.Now) +
                                "                  ".Substring(0, 2 * args.Hops);
                        Stdout.WriteLine(
                            space + "Routing " + args.ToString() + " to " + this.subscribers.Count + " subscriber(s)");
                    }

                    var n = 1;
                    foreach (var callback in this.subscribers.ToArray())
                    {
                        try
                        {
                            if (debug)
                            {
                                Stdout.WriteLine(
                                    space + "  " + (n++) + " : to " + callback.Target.GetHashCode() + " " +
                                    callback.Target);
                            }

                            callback(sender, args);
                        }
                        catch
                        {
                            // TODO remove ? distribute notes ? remove badly noted ?
                        }
                    }
                }

                args.Hops--;
            }
        }

        /// <summary>
        /// The subscribe.
        /// </summary>
        /// <param name="callback">
        /// The callback.
        /// </param>
        public void Subscribe(EventHandler<T> callback)
        {
            {
                // lock (this.locker)
                if (!this.subscribers.Contains(callback))
                {
                    this.subscribers.Add(callback);
                }
            }
        }

        /// <summary>
        /// The to string.
        /// </summary>
        /// <returns>
        /// The string representation
        /// </returns>
        public override string ToString()
        {
            return this.Name;
        }

        /// <summary>
        /// The un chain.
        /// </summary>
        /// <param name="handlerDestination">
        /// The handlerDestination.
        /// </param>
        public void UnChain(RemotableEventHandler<T> handlerDestination)
        {
            // handlerSource -= handlerDestination.GetChainingHandler(handlerSource);
            this.Unsubscribe(handlerDestination.GetChainingHandler(this));
        }

        /// <summary>
        /// The unsubscribe.
        /// </summary>
        /// <param name="callback">
        /// The callback.
        /// </param>
        public void Unsubscribe(EventHandler<T> callback)
        {
            {
                // lock (this.locker)
                if (this.subscribers.Contains(callback))
                {
                    this.subscribers.Remove(callback);
                }

                RemotableEventHandler<T> chainingHandler = null;
                if (this.chainingReverse.ContainsKey(callback))
                {
                    chainingHandler = this.chainingReverse[callback];
                    this.chainingReverse.Remove(callback);
                }

                if (chainingHandler != null && this.chaining.ContainsKey(chainingHandler))
                {
                    this.chaining.Remove(chainingHandler);
                }
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The get chaining handler.
        /// </summary>
        /// <param name="handlerSource">
        /// The handlerSource.
        /// </param>
        /// <returns>
        /// The chaining handler associated to handlerSource.
        /// </returns>
        private EventHandler<T> GetChainingHandler(RemotableEventHandler<T> handlerSource)
        {
            {
                // lock (this.locker)
                if (this.chaining.ContainsKey(handlerSource))
                {
                    return this.chaining[handlerSource];
                }

                EventHandler<T> chainingHandler = (object sender, T args) =>
                    {
                        args.Hops++;
                        this.RaiseEvent(sender, args);
                        args.Hops--;
                    };

                this.chaining[handlerSource] = chainingHandler;
                this.chainingReverse[chainingHandler] = handlerSource;

                return chainingHandler;
            }
        }

        #endregion
    }
}